package com.party.core.service.crowdfund.biz;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.core.model.crowdfund.EventGradation;
import com.party.core.service.crowdfund.IEventGradationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @ClassName EventGradationBizService
 * @Description TODO
 * @Author yifeng
 * @Date 2019/3/20 11:41
 **/
@Service
public class EventGradationBizService {
    @Autowired
    private IEventGradationService eventGradationService;

    /**
     * @param multipleActStr 多场活动字符串
     * @return java.util.List<com.party.core.model.crowdfund.EventGradation>
     * @Author yifeng
     * @Description //TODO
     * @Date 13:50 2019/3/20
     **/
    public List<EventGradation> transfrom(String multipleActStr) {
        List<EventGradation> eventGradations = JSONArray.parseArray(multipleActStr, EventGradation.class);
        Collections.sort(eventGradations, (o1, o2) -> o1.getGradation() > o1.getGradation() ? -1 : 1);

        for (EventGradation eventGradation : eventGradations) {
            if (StringUtils.isNotEmpty(eventGradation.getEndDate())) {
                try {
                    Date parse = DateUtils.parse(eventGradation.getEndDate(), "yyyy-MM-dd HH:mm");
                    eventGradation.setEndTime(parse);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return eventGradations;
    }

    /**
     * @param eventId            主题id
     * @param eventGradationsnew 主题阶段活动
     * @return void
     * @Author yifeng
     * @Description 保存或新增主题阶段信息
     * @Date 11:48 2019/3/20
     **/
    public void saveOrUpdateEventGradation(List<EventGradation> eventGradationsnew, String eventId) {
        List<String> gradationIdsNew = Lists.newArrayList();
        for (EventGradation eventGradation : eventGradationsnew) {
            if (StringUtils.isEmpty(eventGradation.getId())) {
                eventGradation.setEventId(eventId);
                eventGradationService.insert(eventGradation);
            } else {
                eventGradation.setPrice(null);
                eventGradationService.update(eventGradation);
            }
            gradationIdsNew.add(eventGradation.getId());
        }
        List<EventGradation> eventGradations1 = eventGradationService.findByEventId(eventId);
        List<String> gradationIdsOld = LangUtils.transform(eventGradations1, input -> input.getId());
        gradationIdsOld.removeAll(gradationIdsNew);

        for (String oldId : gradationIdsOld) {
            eventGradationService.delete(oldId);
        }
    }
}
